import { login, logout, getInfo } from '@/api/login'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore("user",()=>{
	const token= ref('')
	const id = ref('')
	const name= ref('')
	const avatar= ref('')
	
	function login(userInfo){
		const username = userInfo.username.trim()
		const password = userInfo.password
		const code = userInfo.code
		const uuid = userInfo.uuid
		return new Promise((resolve, reject) => {
		  login(username, password, code, uuid).then(res => {
		    token.value = res.token
		    resolve()
		  }).catch(error => {
		    reject(error)
		  })
		})
	}
	
	function getInfo(){
		return new Promise((resolve, reject) => {
		  getInfo().then(res => {
		    const user = res.user
		    const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
		    id.value = user.userId
		    name.value = user.userName
		    avatar.value = avatar
		    resolve(res)
		  }).catch(error => {
		    reject(error)
		  })
		})
	}
	
	function logOut(){
		return new Promise((resolve, reject) => {
		  logout(this.token).then(() => {
		    token.value = id.value = name.value = avatar.value = ''
		    resolve()
		  }).catch(error => {
		    reject(error)
		  })
		})
	}
	
	return {
		token,
		id,
		name,
		avatar
	}
},{
	persist: {
		key: "userStore",
		paths: ["token",'id','name','avatar']
	}
})